package com.keygenerator;

import org.jetbrains.annotations.NotNull;
import org.springframework.cache.interceptor.KeyGenerator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.lang.reflect.Modifier.isPublic;

public class ArgsFieldGenerator implements KeyGenerator {

    @NotNull
    @Override
    public Object generate(Object target, Method invokedMethod, Object... params) {

        return Arrays.stream(params).filter(Objects::nonNull).flatMap(param -> {

            return Arrays.stream(param.getClass().getDeclaredMethods()).filter(method -> {
                return method.getParameterCount() == 0 && method.getName().startsWith("get") && isPublic(method.getModifiers());
            }).map(method -> {

                try {
                    final Object val = method.invoke(param);
                    if (val != null) {
                        return val.toString();
                    }
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
                return null;
            }).filter(Objects::nonNull);
        }).collect(Collectors.joining("_"));

    }
}
